// pages/user/user.js
const { messageAPI } = require('../../../utils/api');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatar: '/static/images/avatar/user.png',
      nickName: "",
      phone: ""
    },
    nav: [
      { icon: "yzd-other", title: "待付款" },
      { icon: "yzd-time", title: "待服务" },
      { icon: "yzd-document", title: "待评价", status: "已完成" },
      { icon: "yzd-tasklist", title: "已完成" }
    ],
    showLoginModal: false, // 登录模态框显示状态
    showWxLoginModal: false, // 微信授权登录模态框
    showRegisterModal: false, // 注册模态框
    showBindPhoneModal: false, // 绑定手机模态框
    loginForm: {
      phoneNumber: "",
      password: ""
    },
    registerForm: {
      phoneNumber: "",
      password: "",
      nickName: ""
    },
    bindPhoneForm: {
      phoneNumber: "",
      code: ""
    },
    loading: false, // 加载状态
    isLoggedIn: false, // 登录状态
    hasPhone: false, // 是否已绑定手机
    wxUserInfo: null, // 微信用户信息
    code: null, // 微信登录code
    unreadMessageCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.checkLoginStatus();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.checkLoginStatus();
    this.checkPhoneBinding(); // 检查手机号绑定状态
    this.loadUnreadCount(); // 在页面显示时加载未读消息数
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.setData({
        userInfo: {
          ...this.data.userInfo,
          ...userInfo,
          avatar: userInfo.avatarUrl || '/static/images/avatar/user.png'
        },
        isLoggedIn: true,
        hasPhone: !!userInfo.phoneNumber // 检查是否已绑定手机号
      });
      this.getUserInfo(); // 刷新用户信息
    }
  },

  /**
   * 点击登录操作
   */
  login() {
    wx.navigateTo({
      url: '/pages/login/login',
    });
  },

  /**
   * 显示微信授权登录模态框
   */
  showWxLoginModal() {
    this.setData({
      showWxLoginModal: true
    });
  },

  /**
   * 微信授权登录
   */
  wxLogin() {
    this.setData({ loading: true });
    
    // 获取微信登录凭证
    wx.login({
      success: async res => {
        if (res.code) {
          this.setData({ code: res.code });
          
          // 获取微信用户信息
          try {
            const userInfoRes = await this.getUserProfile();
            this.setData({ wxUserInfo: userInfoRes.userInfo });
            
            // 调用微信登录接口
            const loginRes = await this.wxLoginToServer(res.code, userInfoRes.encryptedData, userInfoRes.iv);
            this.handleLoginSuccess(loginRes);
            
            this.setData({ 
              showWxLoginModal: false,
              showBindPhoneModal: !loginRes.data.phoneNumber // 如果未绑定手机，显示绑定手机模态框
            });
            
            wx.showToast({
              title: '登录成功',
              icon: 'success'
            });
          } catch (err) {
            console.error('微信登录失败:', err);
            wx.showToast({
              title: err.message || '微信登录失败',
              icon: 'none'
            });
          }
        } else {
          wx.showToast({
            title: '获取登录凭证失败',
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('微信登录失败:', err);
        wx.showToast({
          title: '微信登录失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  /**
   * 获取用户微信信息
   */
  getUserProfile() {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '用于完善用户资料',
        success: resolve,
        fail: reject
      });
    });
  },

  /**
   * 微信登录接口调用
   */
  wxLoginToServer(code, encryptedData, iv) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: '/app/user/wxLogin',
        method: 'POST',
        data: {
          code,
          encryptedData,
          iv
        },
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.msg || '微信登录失败'));
          }
        },
        fail: (err) => {
          reject(new Error('网络错误，请稍后再试'));
          console.error('微信登录请求失败:', err);
        }
      });
    });
  },

  /**
   * 显示注册模态框
   */
  showRegisterModal() {
    this.setData({
      showRegisterModal: true
    });
  },

  /**
   * 显示绑定手机模态框
   */
  showBindPhoneModal() {
    this.setData({
      showBindPhoneModal: true
    });
  },

  /**
   * 发送手机验证码
   */
  sendCode() {
    const { phoneNumber } = this.data.bindPhoneForm;
    if (!phoneNumber) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 调用发送验证码接口
    wx.request({
      url: '/app/user/sendCode', // 假设存在发送验证码接口
      method: 'POST',
      data: {
        phoneNumber
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          wx.showToast({
            title: '验证码发送成功',
            icon: 'success'
          });
          this.countDown(); // 倒计时
        } else {
          wx.showToast({
            title: res.data.msg || '验证码发送失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        console.error('发送验证码失败:', err);
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  /**
   * 倒计时函数
   */
  countDown() {
    let time = 60;
    const interval = setInterval(() => {
      time--;
      if (time <= 0) {
        clearInterval(interval);
        this.setData({ canSendCode: true });
      } else {
        this.setData({ canSendCode: false, codeTime: `${time}s` });
      }
    }, 1000);
  },

  /**
   * 输入框内容变化处理
   */
  inputChange(e) {
    const { field, form } = e.currentTarget.dataset;
    if (form === 'login') {
      this.setData({
        [`loginForm.${field}`]: e.detail.value
      });
    } else if (form === 'register') {
      this.setData({
        [`registerForm.${field}`]: e.detail.value
      });
    } else if (form === 'bindPhone') {
      this.setData({
        [`bindPhoneForm.${field}`]: e.detail.value
      });
    }
  },

  /**
   * 提交登录表单
   */
  submitLogin() {
    const { phoneNumber, password } = this.data.loginForm;
    
    // 表单验证
    if (!phoneNumber || !password) {
      wx.showToast({
        title: '请输入手机号和密码',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 调用登录API
    this.loginToServer(phoneNumber, password)
      .then(res => {
        this.handleLoginSuccess(res);
        this.hideLoginModal();
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
      })
      .catch(err => {
        wx.showToast({
          title: err.message || '登录失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  /**
   * 注册用户
   */
  register() {
    const { phoneNumber, password, nickName } = this.data.registerForm;
    
    // 表单验证
    if (!phoneNumber || !password || !nickName) {
      wx.showToast({
        title: '请填写完整注册信息',
        icon: 'none'
      });
      return;
    }
    
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 调用注册API
    this.registerToServer(phoneNumber, password, nickName)
      .then(res => {
        this.handleLoginSuccess(res);
        this.hideRegisterModal();
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
      })
      .catch(err => {
        wx.showToast({
          title: err.message || '注册失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  /**
   * 注册接口调用
   */
  registerToServer(phoneNumber, password, nickName) {
    return new Promise((resolve, reject) => {
      // 模拟注册验证
      if (phoneNumber === '18296995790') {
        // 模拟成功响应
        setTimeout(() => {
          resolve({
            code: 200,
            msg: '注册成功',
            data: {
              id: 1,
              phoneNumber: '18296995790',
              nickName: nickName || '张角',
              avatarUrl: '/static/images/avatar/avatar.png',
              token: 'mock_token_' + Date.now(),
              createTime: new Date().toISOString()
            }
          });
        }, 500); // 模拟网络延迟
      } else {
        // 模拟失败响应
        setTimeout(() => {
          reject(new Error('注册失败，请稍后再试'));
        }, 300);
      }
    });
  },

  /**
   * 绑定手机号
   */
  bindPhone() {
    if (!this.data.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/my/bindPhone/bindPhone'
    });
  },

  /**
   * 检查用户是否已绑定手机号
   */
  checkPhoneBinding() {
    const userInfo = wx.getStorageSync('userInfo');
    console.log('userInfo:', userInfo); // 调试用
    if (userInfo && (userInfo.phoneNumber || userInfo.phone)) {
      this.setData({
        hasPhone: true
      });
    } else {
      this.setData({
        hasPhone: false
      });
    }
  },

  /**
   * 调用登录API
   */
  loginToServer(phoneNumber, password) {
    return new Promise((resolve, reject) => {
      // 模拟账号验证
      if (phoneNumber === '18296995790' && password === '123') {
        // 模拟成功响应
        setTimeout(() => {
          resolve({
            code: 200,
            msg: '登录成功',
            data: {
              id: 1,
              phoneNumber: '18296995790',
              nickName: '张角',
              avatarUrl: '/static/images/avatar/avatar.png',
              token: 'mock_token_' + Date.now(),
              createTime: new Date().toISOString()
            }
          });
        }, 500); // 模拟网络延迟
      } else {
        // 模拟失败响应
        setTimeout(() => {
          reject(new Error('手机号或密码错误'));
        }, 300);
      }
    });
  },

  /**
   * 处理登录成功
   */
  handleLoginSuccess(res) {
    // 存储用户信息和token
    wx.setStorageSync('userInfo', res.data);
    wx.setStorageSync('token', res.data.token);
    
    // 更新页面数据
    this.setData({
      userInfo: {
        ...this.data.userInfo,
        ...res.data,
        avatar: res.data.avatarUrl || '/static/images/avatar/user.png',
        phone: res.data.phoneNumber || ""
      },
      isLoggedIn: true,
      showLoginModal: false,
      showRegisterModal: false,
      showBindPhoneModal: false,
      hasPhone: !!res.data.phoneNumber
    });
  },

  /**
   * 退出登录
   */
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的用户信息和token
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          
          // 更新页面状态
          this.setData({
            userInfo: {
              avatar: '/static/images/avatar/user.png',
              nickName: "",
              phone: ""
            },
            isLoggedIn: false,
            hasPhone: false
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'none'
          });
        }
      }
    });
  },

  /**
   * 防止触摸穿透
   */
  preventTouchMove() {},

  /**
   * 隐藏模态框
   */
  hideModal(e) {
    const { modal } = e.currentTarget.dataset;
    this.setData({
      [modal]: false,
      loading: false
    });
  },

  /**
   * 获取用户信息
   */
  getUserInfo() {
    // 模拟获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo && userInfo.phoneNumber === '18296995790') {
      // 返回模拟的用户信息
      setTimeout(() => {
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...userInfo,
            avatar: userInfo.avatarUrl || '/static/images/avatar/user.png'
          },
          hasPhone: !!userInfo.phoneNumber
        });
      }, 200);
    } else {
      // 如果没有用户信息，尝试从本地存储获取
      if (userInfo) {
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...userInfo,
            avatar: userInfo.avatarUrl || '/static/images/avatar/user.png'
          },
          hasPhone: !!userInfo.phoneNumber
        });
      }
    }
  },

  /**
   * 更新用户信息
   */
  updateUserInfo() {
    wx.navigateTo({
      url: '/pages/user/editInfo'
    });
  },

  /**
   * 其他页面功能...
   */
  toPage(e) {
    if (!this.data.isLoggedIn) {
      this.showLoginTip();
      return;
    }
    let { page, value, status } = e.currentTarget.dataset;
    
    // The `nav` items pass 'value', while the list items might pass 'page' or 'status'
    // We prioritize 'status' if it exists, otherwise use 'value'
    const finalStatus = status || value;

    if (page === 'message') {
        wx.navigateTo({ url: '/pages/my/chat/index' });
    } else {
        wx.navigateTo({
            url: `/pages/my/serviceOrder/serviceOrder?status=${finalStatus}`
        });
    }
  },

  /**
   * 显示登录提示
   */
  showLoginTip() {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    });
  },

  updeta() {
    this.setData({
      updeta: !this.data.updeta
    });
  },

  /**
   * 隐藏登录模态框
   */
  hideLoginModal() {
    this.setData({
      showLoginModal: false
    });
  },

  /**
   * 隐藏注册模态框
   */
  hideRegisterModal() {
    this.setData({
      showRegisterModal: false
    });
  },

  /**
   * 隐藏微信登录模态框
   */
  hideWxLoginModal() {
    this.setData({
      showWxLoginModal: false
    });
  },

  /**
   * 隐藏绑定手机模态框
   */
  hideBindPhoneModal() {
    this.setData({
      showBindPhoneModal: false
    });
  },

  async loadUnreadCount() {
    if (!this.data.isLoggedIn) {
      this.setData({ unreadMessageCount: 0 });
      return;
    }
    try {
      const res = await messageAPI.list({ pageNum: 1, pageSize: 999 }); // Fetch all conversations
      const conversations = res.data.list || [];
      let totalUnread = 0;
      const processedIds = new Set();

      conversations.forEach(conv => {
        // Since getMessageList returns a flat list of messages, we group by orderId
        if (!processedIds.has(conv.orderId) && conv.unreadCount > 0) {
          totalUnread += conv.unreadCount;
          processedIds.add(conv.orderId);
        }
      });

      this.setData({
        unreadMessageCount: totalUnread,
      });
    } catch (error) {
      console.error('获取未读消息数失败:', error);
      this.setData({ unreadMessageCount: 0 });
    }
  }
});